package fw.qaz.asmx.reader.utils;

import android.content.Context;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import fw.qaz.asmx.reader.adapter.item.BookItem;

public abstract class BookShelfUtil
{
    public static File bookJsonFile;

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    //在Application启动后调用一次即可
    public static void initBookShelfFile(Context context)
    {
        bookJsonFile = new File(context.getFilesDir() + File.separator + "book.json.asmx");

        if(!bookJsonFile.exists())
        {
            FileProcess.writeFile(bookJsonFile.getAbsolutePath(),
                                  new JSONArray().toString().getBytes(), false);
        }
    }

    //从json文件中获取书，并返回ArrayList传给书架的数据源
    public static ArrayList<BookItem> getBooksFromJsonFile()
    {
        String jsonString;
        ArrayList<BookItem> books = new ArrayList<>();
        byte[] jsonByte = FileProcess.readFile(bookJsonFile.getAbsolutePath());
        if (jsonByte != null)
        {
            jsonString = new String(jsonByte);
            try
            {
                JSONArray jsArray = new JSONArray(jsonString);
                for (int i = 0; i < jsArray.length(); i++)
                {
                    JSONObject jsObj = jsArray.getJSONObject(i);
                    books.add(new BookItem(jsObj.getString("bookName"), "没有图",
                                           jsObj.getString("path"),
                                           (int) jsObj.getLong("readProgress")));
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return books;
    }

    //读文件
    public static String readBookJsonFile(File filePath)
    {
        //新的读文件的方式
        byte[] bytes = FileProcess.readFile(filePath.getAbsolutePath());
        if (bytes != null)
        {
            return new String(bytes);
        }
        return null;
    }

    //向文件中添加一本书的
    public static boolean addBookToJsonFile(File f)
    {
        String S = readBookJsonFile(bookJsonFile);//获取原数据

        String path = f.getAbsolutePath();
        String bookName = f.getName();

        if (!checkBookIsInFile(bookName, path, S)) //检查书是否存在
        {
            try
            {
                JSONArray jsonArray = new JSONArray(S);
                JSONObject book = new JSONObject();
                book.put("bookName", bookName);
                book.put("path", path);
                book.put("readProgress", 0);
                jsonArray.put(book);
                FileProcess.writeFile(bookJsonFile.getAbsolutePath(),
                                      jsonArray.toString().getBytes(),
                                      false);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

    //保存进度
    public static boolean saveBookMaxProgress(File f, int newProgress)
    {
        String S = readBookJsonFile(bookJsonFile);//获取原数据
        String path = f.getAbsolutePath();
        String bookName = f.getName();
        try
        {
            JSONArray jsonArray = new JSONArray(S);
            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject book = jsonArray.getJSONObject(i);
                if (book.getString("bookName").equals(bookName) &&
                        book.getString("path").equals(path))
                {
                    book.put("readProgress",newProgress);
                    FileProcess.writeFile(bookJsonFile.getAbsolutePath(),
                            jsonArray.toString().getBytes(),
                            false);
                    return true;
                }
            }
            return false;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    //获取最大进度
    public static int getMaxProgress(String bookName, String path)
    {
        String S = readBookJsonFile(bookJsonFile);//获取原数据
        try
        {
            JSONArray jsonArray = new JSONArray(S);
            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject book = jsonArray.getJSONObject(i);
                if (book.getString("bookName").equals(bookName) &&
                        book.getString("path").equals(path))
                {
                    return book.getInt("readProgress");
                }
            }
            return 0;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return 0;
        }
    }



    //检查要添加的书,是否存在，存在则不添加
    public static boolean checkBookIsInFile(String bookName, String path, String JsonString)
    {
        try
        {
            JSONArray jsonArray = new JSONArray(JsonString);
            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject book = jsonArray.getJSONObject(i);
                if (book.getString("bookName").equals(bookName) &&
                    book.getString("path").equals(path))
                {
                    return true;
                }
            }
            return false;
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
    }

    //用书名和路径匹配删除文件中的书
    public static void deleteBookFromJsonFile(String bookName, String path)
    {
        String S = readBookJsonFile(bookJsonFile);//获取原数据
        try
        {
            /**
             * 看到这一段觉得很诡异- -<br/>
             * 不管是JSONArray还是JSONObject，<br/>
             * 都有remove方法，不用做拷贝吧。
             */

            JSONArray jsonArray = new JSONArray(S);
            JSONArray jsonArrayT = new JSONArray();//目标json
            for (int i = 0; i < jsonArray.length(); i++)
            {
                JSONObject book = jsonArray.getJSONObject(i);

                if (book.getString("bookName").equals(bookName) &&
                    book.getString("path").equals(path))
                {

                }
                else
                {
                    jsonArrayT.put(book);
                }
            }
            FileProcess.writeFile(bookJsonFile.getAbsolutePath(), jsonArrayT.toString().getBytes(),
                                  false);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
